import OpenAI from 'openai'

export default class Dialogue {
  createDialogue(apiUrl) {
    const openai = new OpenAI({
      // 若没有配置环境变量，请用百炼API Key将下行替换为：apiKey: "sk-xxx",
      apiKey: 'sk-xxx',
      baseURL: apiUrl
    })

    return async function dialogue(messages = [{ role: 'user', content: '你好' }], options = {}) {
      return new Promise((resolve, reject) => {
        const { apiKey = '', ...opts } = options
        openai.apiKey = apiKey
        openai.chat.completions
          .create({
            model: 'moonshot-v1-8k', //模型列表
            messages,
            stream: false,
            ...opts
          })
          .then((completion) => {
            resolve(completion?.choices?.[0]?.message?.content || '对话失败')
          })
          .catch((err) => {
            reject({
              message: err?.message || err?.error?.message || '对话失败'
            })
          })
      })
    }
  }
}
